const User = require('../models/User');
const wechatService = require('./wechatService');

class UserService {
  // 同步用户信息
  async syncUser(openid) {
    try {
      const wechatUserInfo = await wechatService.getUserInfo(openid);
      
      const userData = {
        openid: wechatUserInfo.openid,
        nickname: wechatUserInfo.nickname,
        sex: wechatUserInfo.sex,
        province: wechatUserInfo.province,
        city: wechatUserInfo.city,
        country: wechatUserInfo.country,
        headimgurl: wechatUserInfo.headimgurl,
        subscribe: wechatUserInfo.subscribe === 1,
        subscribe_time: wechatUserInfo.subscribe_time ? new Date(wechatUserInfo.subscribe_time * 1000) : null,
        language: wechatUserInfo.language,
        remark: wechatUserInfo.remark,
        groupid: wechatUserInfo.groupid,
        tagid_list: wechatUserInfo.tagid_list,
        subscribe_scene: wechatUserInfo.subscribe_scene,
        qr_scene: wechatUserInfo.qr_scene,
        qr_scene_str: wechatUserInfo.qr_scene_str
      };
      
      // 更新或创建用户
      const user = await User.findOneAndUpdate(
        { openid },
        userData,
        { upsert: true, new: true }
      );
      
      return user;
    } catch (error) {
      console.error('同步用户信息失败:', error);
      throw error;
    }
  }

  // 获取本地用户信息
  async getUser(openid) {
    return await User.findOne({ openid });
  }

  // 获取所有用户
  async getUsers(page = 1, limit = 10) {
    const skip = (page - 1) * limit;
    return await User.find()
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);
  }

  // 更新用户备注
  async updateUserRemark(openid, remark) {
    return await User.findOneAndUpdate(
      { openid },
      { remark },
      { new: true }
    );
  }
}

module.exports = new UserService();